package com.util;

import com.bean.Farmer;
import com.bean.Users;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;

public class SelectFarmer {
    private String id = "sa";
    private String pwd = "123456";
    private String url = "jdbc:sqlserver://127.0.0.1:1433;databaseName=FarmProductSalesSystem";
    private List<Farmer> farmerList;
    public List<Farmer> getFarmerData(){
        farmerList = new ArrayList<>();
        try {
            //加载驱动
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //获取连接
        Connection conn = null;
        Statement stat = null;
        ResultSet rs = null;
        try {
            conn = DriverManager.getConnection(url,id,pwd);
            String sql = "select * from Farmer";
            stat = conn.createStatement(); //用于执行sql语句
            rs = stat.executeQuery(sql); //返回查询后的结果
            while(rs.next()){
                String FarmerID = rs.getString("FarmerID");
                String FarmerName = rs.getString("FarmerName");
                String Gender = rs.getString("Gender");
                String Password = rs.getString("Password");
                String Address = rs.getString("Address");
                String PhoneNumber = rs.getString("PhoneNumber");
                Farmer farmer = new Farmer(Integer.parseInt(FarmerID),FarmerName,Password,Gender,Address,PhoneNumber);
                farmerList.add(farmer);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("连接数据库失败！");
        }finally{
            //关闭coon
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

            //关闭stat
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

            //关闭rs
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return farmerList;
    }

    public int getFarmerID(){
        List<Farmer> list = getFarmerData();
        int ID = 0;
        for(Farmer f:list)
        {
            ID = f.getFarmerId();
        }
        return ID;
    }

}
